﻿// pages/team-order-detail/team-order-detail.js
Page({
  data: {
    loading: true,
    orderId: '',
    order: null,
    teamInfo: null,
    actionHistory: [],
    
    // 弹窗状态
    showAcceptModal: false,
    showRejectModal: false,
    showStatusModal: false,
    
    // 表单数据
    estimatedPrice: '',
    estimatedDays: '',
    teamNotes: '',
    rejectReason: '',
    selectedStatus: '',
    statusNote: '',
    
    // 拒绝原因选项
    rejectReasons: [
      '时间冲突',
      '距离太远',
      '专业不符',
      '价格不合适',
      '其他原因'
    ]
  },

  onLoad(options) {
    console.log('订单详情页面加载，订单ID:', options.id)
    
    if (options.id) {
      this.setData({ orderId: options.id })
      this.loadOrderDetail(options.id)
    } else {
      wx.showToast({
        title: '订单ID无效',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  // 加载订单详情
  async loadOrderDetail(orderId) {
    console.log('📄 开始加载订单详情:', orderId)
    wx.showLoading({ title: '加载中...' })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'getOrderDetail',
          orderId: orderId
        }
      })
      
      console.log('📄 云函数返回结果:', result)
      
      if (result.result && result.result.success) {
        const orderData = result.result.data
        
        console.log('📋 订单详情数据:', orderData.order)
        console.log('👥 施工队伍信息:', orderData.teamInfo)
        console.log('🔍 按钮显示判断:')
        console.log('  - order.teamId:', orderData.order.teamId)
        console.log('  - teamInfo._id:', orderData.teamInfo._id)
        console.log('  - 是否已接单:', orderData.order.teamId === orderData.teamInfo._id)
        console.log('  - 订单状态:', orderData.order.status)
        console.log('  - 是否显示接单按钮:', !orderData.order.teamId || orderData.order.teamId !== orderData.teamInfo._id)
        console.log('  - 是否显示更新状态按钮:', orderData.order.teamId === orderData.teamInfo._id && orderData.order.status !== 'completed')
        
        this.setData({
          order: orderData.order,
          teamInfo: orderData.teamInfo,
          actionHistory: orderData.actionHistory || [],
          loading: false
        })
        console.log('✅ 订单详情加载成功')
      } else {
        const errorMsg = result.result ? result.result.error : '未知错误'
        console.error('❌ 加载订单详情失败:', errorMsg)
        wx.showToast({
          title: errorMsg || '加载失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      console.error('❌ 加载订单详情异常:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 显示接单弹窗
  showAcceptModal() {
    this.setData({
      showAcceptModal: true,
      estimatedPrice: '',
      estimatedDays: '',
      teamNotes: ''
    })
  },

  // 隐藏接单弹窗
  hideAcceptModal() {
    this.setData({ showAcceptModal: false })
  },

  // 显示拒单弹窗
  showRejectModal() {
    this.setData({
      showRejectModal: true,
      rejectReason: ''
    })
  },

  // 隐藏拒单弹窗
  hideRejectModal() {
    this.setData({ showRejectModal: false })
  },

  // 显示状态更新菜单
  showStatusMenu() {
    console.log('🔄 点击状态更新按钮')
    console.log('当前订单状态:', this.data.order?.status)
    
    // 根据当前订单状态动态生成可选状态
    const currentStatus = this.data.order?.status
    let statusOptions = []
    let statusMap = {}
    
    // 根据当前状态确定可选的下一状态
    switch(currentStatus) {
      case 'accepted':
        statusOptions = ['开始查勘']
        statusMap = { 0: 'surveying' }
        break
      case 'surveying':
        statusOptions = ['开始设计']
        statusMap = { 0: 'designing' }
        break
      case 'designing':
        statusOptions = ['完成报价']
        statusMap = { 0: 'quoted' }
        break
      case 'quoted':
        statusOptions = ['开始施工']
        statusMap = { 0: 'in_progress' }
        break
      case 'in_progress':
        statusOptions = ['开始验收']
        statusMap = { 0: 'testing' }
        break
      case 'testing':
        statusOptions = ['完成订单']
        statusMap = { 0: 'completed' }
        break
      default:
        console.log('❌ 当前状态不支持更新:', currentStatus)
        wx.showToast({
          title: `当前状态"${currentStatus}"暂不支持更新`,
          icon: 'none'
        })
        return
    }
    
    console.log('📋 可选状态选项:', statusOptions)
    
    if (statusOptions.length === 0) {
      wx.showToast({
        title: '当前状态已是最终状态',
        icon: 'none'
      })
      return
    }
    
    wx.showActionSheet({
      itemList: statusOptions,
      success: (res) => {
        console.log('✅ 选择了状态，索引:', res.tapIndex)
        console.log('映射的状态值:', statusMap[res.tapIndex])
        
        this.setData({
          showStatusModal: true,
          selectedStatus: statusMap[res.tapIndex],
          statusNote: ''
        })
        
        console.log('📋 弹窗状态已设置:', this.data.showStatusModal)
      },
      fail: (error) => {
        console.log('❌ 状态选择取消或失败:', error)
      }
    })
  },

  // 隐藏状态更新弹窗
  hideStatusModal() {
    this.setData({ showStatusModal: false })
  },

  // 表单输入处理
  onEstimatedPriceInput(e) {
    this.setData({ estimatedPrice: e.detail.value })
  },

  onEstimatedDaysInput(e) {
    this.setData({ estimatedDays: e.detail.value })
  },

  onTeamNotesInput(e) {
    this.setData({ teamNotes: e.detail.value })
  },

  onStatusNoteInput(e) {
    this.setData({ statusNote: e.detail.value })
  },

  onRejectReasonChange(e) {
    const index = e.detail.value
    this.setData({
      rejectReason: this.data.rejectReasons[index]
    })
  },

  // 确认接单
  async confirmAcceptOrder() {
    const { estimatedPrice, estimatedDays } = this.data
    
    if (!estimatedPrice) {
      wx.showToast({
        title: '请填写预估价格',
        icon: 'none'
      })
      return
    }
    
    if (!estimatedDays) {
      wx.showToast({
        title: '请填写预估工期',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '接单中...' })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'acceptOrder',
          orderId: this.data.orderId,
          estimatedPrice: parseFloat(estimatedPrice),
          estimatedDays: estimatedDays,
          notes: this.data.teamNotes
        }
      })
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '接单成功',
          icon: 'success'
        })
        
        this.hideAcceptModal()
        // 重新加载订单详情
        await this.loadOrderDetail(this.data.orderId)
        
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.result.error || '接单失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('接单失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 确认拒单
  async confirmRejectOrder() {
    if (!this.data.rejectReason) {
      wx.showToast({
        title: '请选择拒绝原因',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '处理中...' })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'rejectOrder',
          orderId: this.data.orderId,
          reason: this.data.rejectReason
        }
      })
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '已拒绝订单',
          icon: 'success'
        })
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.result.error || '操作失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('拒单失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 确认更新状态
  async confirmUpdateStatus() {
    console.log('🔄 开始确认更新状态')
    console.log('选中的状态:', this.data.selectedStatus)
    console.log('状态说明:', this.data.statusNote)
    console.log('订单ID:', this.data.orderId)
    
    if (!this.data.selectedStatus) {
      console.log('❌ 未选择状态')
      wx.showToast({
        title: '请选择状态',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({ title: '更新中...' })
    
    try {
      console.log('📡 准备调用云函数...')
      const result = await wx.cloud.callFunction({
        name: 'teamOrderManager',
        data: {
          action: 'updateOrderStatus',
          orderId: this.data.orderId,
          status: this.data.selectedStatus,
          notes: this.data.statusNote
        }
      })
      
      console.log('📡 云函数返回结果:', result)
      
      if (result.result.success) {
        wx.hideLoading()
        wx.showToast({
          title: '状态更新成功',
          icon: 'success'
        })
        
        this.hideStatusModal()
        // 重新加载订单详情
        await this.loadOrderDetail(this.data.orderId)
        
      } else {
        wx.hideLoading()
        wx.showToast({
          title: result.result.error || '更新失败',
          icon: 'none'
        })
      }
      
    } catch (error) {
      wx.hideLoading()
      console.error('更新状态失败:', error)
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  },

  // 联系客户
  contactCustomer() {
    const phone = this.data.order?.phone
    
    if (!phone) {
      wx.showToast({
        title: '客户电话号码不存在',
        icon: 'none'
      })
      return
    }
    
    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => {
        console.log('📞 成功发起通话')
      },
      fail: (error) => {
        // 用户取消不显示错误，其他错误才提示
        if (error.errMsg !== 'makePhoneCall:fail cancel') {
          console.error('拨打电话失败:', error)
          wx.showToast({
            title: '拨打失败',
            icon: 'none'
          })
        }
      }
    })
  },

  // 查看位置
  viewLocation() {
    const order = this.data.order
    
    if (!order || !order.latitude || !order.longitude) {
      wx.showToast({
        title: '位置信息不存在',
        icon: 'none'
      })
      return
    }
    
    wx.openLocation({
      latitude: order.latitude,
      longitude: order.longitude,
      name: order.address,
      address: order.address,
      fail: (error) => {
        console.error('打开位置失败:', error)
        wx.showToast({
          title: '打开地图失败',
          icon: 'none'
        })
      }
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 格式化日期
  formatDate(dateStr) {
    if (!dateStr) return ''
    
    try {
      let date
      
      // 处理不同的日期格式
      if (typeof dateStr === 'string') {
        date = new Date(dateStr)
      } else if (dateStr instanceof Date) {
        date = dateStr
      } else if (typeof dateStr === 'number') {
        date = new Date(dateStr)
      } else {
        date = new Date(String(dateStr))
      }
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.warn('❌ 无效的日期格式:', dateStr)
        return String(dateStr)
      }
      
      const now = new Date()
      const diff = now - date
      
      if (diff < 86400000) { // 24小时内
        if (diff < 3600000) { // 1小时内
          const minutes = Math.floor(diff / 60000)
          return `${minutes}分钟前`
        } else {
          const hours = Math.floor(diff / 3600000)
          return `${hours}小时前`
        }
      } else {
        // 手动格式化，确保兼容性
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        return `${month}月${day}日`
      }
    } catch (error) {
      console.error('❌ 格式化日期失败:', error, '原始数据:', dateStr)
      return String(dateStr)
    }
  },

  // 获取状态信息
  getStatusInfo(status) {
    const statusMap = {
      waiting_team: { text: '等待接单', color: '#fa8c16', bgColor: '#fff2e8' },
      accepted: { text: '已接单', color: '#1890ff', bgColor: '#e6f7ff' },
      surveying: { text: '查勘中', color: '#722ed1', bgColor: '#f9f0ff' },
      designing: { text: '设计中', color: '#eb2f96', bgColor: '#fff0f6' },
      quoted: { text: '已报价', color: '#13c2c2', bgColor: '#e6fffb' },
      in_progress: { text: '施工中', color: '#fa541c', bgColor: '#fff2e8' },
      testing: { text: '验收中', color: '#2f54eb', bgColor: '#f0f5ff' },
      completed: { text: '已完成', color: '#52c41a', bgColor: '#f6ffed' }
    }
    return statusMap[status] || statusMap.waiting_team
  },

  // 获取紧急程度信息
  getUrgencyInfo(urgency) {
    const urgencyMap = {
      low: { text: '一般', color: '#52c41a' },
      normal: { text: '普通', color: '#1890ff' },
      high: { text: '紧急', color: '#fa8c16' },
      urgent: { text: '特急', color: '#f5222d' }
    }
    return urgencyMap[urgency] || urgencyMap.normal
  }
})
